<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Db;
use think\exception\HttpResponseException;
// 应用公共文件
// 引入错误编码
include_once APP_PATH . 'errcode.php';
// 引入自定义的define
include_once 'define.php';


function responseJson($data = [], $code = 0)
{
    $msg = $GLOBALS['ERR_CODE'][$code] ? $GLOBALS['ERR_CODE'][$code] : '';
    throw new HttpResponseException(json(['code' => $code, 'msg' => $msg, 'data' => $data]));
}

function http_get($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $output = curl_exec($ch);
    curl_close($ch);
    $arr_out = json_decode($output);
    return $arr_out;
}

function http_post_data($url, $data)
{

    //将数组转成json格式
    $data = json_encode($data);

    //1.初始化curl句柄
    $ch = curl_init();

    //2.设置curl
    //设置访问url
    curl_setopt($ch, CURLOPT_URL, $url);

    //捕获内容，但不输出
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //模拟发送POST请求
    curl_setopt($ch, CURLOPT_POST, 1);

    //发送POST请求时传递的参数
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    //设置头信息
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data))
    );

    //3.执行curl_exec($ch)
    $return_content = curl_exec($ch);

    //如果获取失败返回错误信息
    if ($return_content === FALSE) {
        $return_content = curl_errno($ch);
    }

    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    //4.关闭curl
    curl_close($ch);

    return array($return_code, $return_content);
}

/*
 *分页
 * @param array $list  数据
 * @param int   $page  页码
 * @param int   $num   一页多少条记录
 */
function paging($list, $page, $num = 10)
{
    $start = ($page - 1) * $num;
    $total = sizeof($list);
    $data = array_slice($list, $start, $num);
    $Data = [
        'total' => $total,
        'data' => $data,
    ];
    return $Data;
}

//自己封装的随机生成的盐函数
function salt()
{
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    mt_srand(10000000 * (double)microtime());
    for ($i = 0, $salt = '', $lc = strlen($chars) - 1; $i < 4; $i++) {
        $salt .= $chars[mt_rand(0, $lc)];
    }
    return $salt;
}

/**
 * 二维数组根据首字母分组排序
 * @param  array  $data      二维数组
 * @param  string $targetKey 首字母的键名
 * @return array             根据首字母关联的二维数组
 */
function groupByInitials(array $data, $targetKey = 'name')
{
    $data = array_map(function ($item) use ($targetKey) {
        $arr = array_merge($item, [
            'initials' => getInitials($item[$targetKey]),
        ]);
        return $arr;
    }, $data);
//    print_r($data);exit();
    $data = sortInitials($data);
    return $data;
}

/**
 * 按字母排序
 * @param  array  $data
 * @return array
 */
function sortInitials(array $data)
{
    $sortData = [];
    foreach ($data as $key => $value) {
        $sortData[$value['initials']][] = $value;
    }
    ksort($sortData);
    $sort_data = [];
    foreach ($sortData as $k => $v){
        $sort_data[] = [
            'name' => $k,
            'arr'  => $v
        ];
    }
    return $sort_data;
}

/**
 * 获取首字母
 * @param  string $str 汉字字符串
 * @return string 首字母
 */
function getInitials($str)
{
    if (empty($str)) {return '';}
    $fchar = ord($str{0});
    if ($fchar >= ord('A') && $fchar <= ord('z')) {
        return strtoupper($str{0});
    }

    $s1  = iconv('UTF-8', 'gb2312', $str);
    $s2  = iconv('gb2312', 'UTF-8', $s1);
    $s   = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284) {
        return 'A';
    }

    if ($asc >= -20283 && $asc <= -19776) {
        return 'B';
    }

    if ($asc >= -19775 && $asc <= -19219) {
        return 'C';
    }

    if ($asc >= -19218 && $asc <= -18711) {
        return 'D';
    }

    if ($asc >= -18710 && $asc <= -18527) {
        return 'E';
    }

    if ($asc >= -18526 && $asc <= -18240) {
        return 'F';
    }

    if ($asc >= -18239 && $asc <= -17923) {
        return 'G';
    }

    if ($asc >= -17922 && $asc <= -17418) {
        return 'H';
    }

    if ($asc >= -17417 && $asc <= -16475) {
        return 'J';
    }

    if ($asc >= -16474 && $asc <= -16213) {
        return 'K';
    }

    if ($asc >= -16212 && $asc <= -15641) {
        return 'L';
    }

    if ($asc >= -15640 && $asc <= -15166) {
        return 'M';
    }

    if ($asc >= -15165 && $asc <= -14923) {
        return 'N';
    }

    if ($asc >= -14922 && $asc <= -14915) {
        return 'O';
    }

    if ($asc >= -14914 && $asc <= -14631) {
        return 'P';
    }

    if ($asc >= -14630 && $asc <= -14150) {
        return 'Q';
    }

    if ($asc >= -14149 && $asc <= -14091) {
        return 'R';
    }

    if ($asc >= -14090 && $asc <= -13319) {
        return 'S';
    }

    if ($asc >= -13318 && $asc <= -12839) {
        return 'T';
    }

    if ($asc >= -12838 && $asc <= -12557) {
        return 'W';
    }

    if ($asc >= -12556 && $asc <= -11848) {
        return 'X';
    }

    if ($asc >= -11847 && $asc <= -11056) {
        return 'Y';
    }

    if ($asc >= -11055 && $asc <= -10247) {
        return 'Z';
    }

    return null;
}

/*生成20位唯一订单号码，格式：YYYY-MMDD-HHII-SS-NN,NN-CC，其中：YYYY=年份，MM=月份，DD=日期，HH=24格式小时，II=分，SS=秒，NNNN=随机数，CC=检查码
*/
function order_number()
{

    // @date_default_timezone_set("PRC");
    //订单号码主体（YYYYMMDDHHIISSNNNNNN）
    $order_id_main = date('YmdHis') . rand(1000, 9999);
    //订单号码主体长度
    $order_id_len = strlen($order_id_main);
    $order_id_sum = 0;
    for ($i = 0; $i < $order_id_len; $i++) {
        $order_id_sum += (int)(substr($order_id_main, $i, 1));
    }
    //唯一订单号码（YYYYMMDDHHIISSNNNNNNCC）
    $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
    return $order_id;
}

//生成摄影师编号四位
function author_no()
{
    $author_no = Db::name('author')->select();
    if(empty($author_no)){
        $number = '0001';
    }else{
        $arr = [];
        foreach ($author_no as $k => $v){
            $arr[] = $v['author_no'];
        }
        $number = max($arr) + 1;
        $length = strlen($number);
        if ($length == 1){
            $number = '000'.$number;
        }elseif ($length == 2){
            $number = '00'.$number;
        }elseif ($length == 3){
            $number = '0'.$number;
        }
    }
    return $number;
}

/**
 * 生成作品编号
 * @param  string $author_no 摄影师编号
 * @return string $goods_no 作品编号
 */
function goods_no($author_no){
    if (empty($author_no)){ //摄影师编号不能为空
        responseJson([],2006);
    }
    //查询此摄影师的作品数量
    $goods_num = Db::name('goods')->where('author_no',$author_no)->count();
    if ($goods_num >= 99){  //每个摄影师作品数量不能超过99个
        responseJson([],2010);
    }
    $photo_num = Db::name('photo')->where('author_no',$author_no)->count();
    if ($photo_num >= 99){  //每个摄影师照片数量不能超过99个
        responseJson([],2011);
    }
    $num = $goods_num+1;
    if (strlen($num) == 1){
        $goods_no = $author_no.'-'.'0'.$num;
    }else{
        $goods_no = $author_no.'-'.$num;
    }
    return $goods_no;
}

/**
 * 生成照片编号
 * @param  string $author_no 摄影师编号
 * @param string $goods_no 作品编号
 * @return string $photo_no 作品编号
 */
function photo_no($author_no,$goods_no){
    if (empty($author_no)){ //摄影师编号不能为空
        responseJson([],2006);
    }
    if (empty($goods_no)){
        responseJson([],3012);
    }
    $photo_num = Db::name('photo')->where('author_no',$author_no)->count();
    if ($photo_num >= 99){
        responseJson([],2011);
    }else{
        $photo_num = $photo_num + 1;
    }
    $num = '';
    if (strlen($photo_num) == 1){
        $num = '0'.$photo_num;
    }elseif (strlen($photo_num) == 2){
        $num = $photo_num;
    }
    $goods_info = Db::name('goods')->where('goods_no',$goods_no)->field('goods_structure,goods_suite')->find();
    if (empty($goods_info)){
        responseJson([],1004);
    }
    $goods_suite = $goods_info['goods_suite'];
    $photo_no = '';
    if ($goods_info['goods_structure'] == 1){
        if (strlen($goods_info['goods_suite']) == 1){
            $goods_suite = '0'.$goods_info['goods_suite'];
        }
        $photo_no = $goods_no.'-'.'0'.$goods_suite.'-'.$num;
    }elseif ($goods_info['goods_structure'] == 2){
        $photo = Db::name('photo')->where(['goods_no'=>$goods_no])->count();
        $photo = $photo + 1;
        if (strlen($photo) == 1){
            $photo = '0'.$photo;
        }
        $photo_no = $goods_no.'-'.$goods_suite.$photo.'-'.$num;
    }
    return $photo_no;
}

// 应用公共文件
function upload($data)
{
    if (strpos($data, 'video')) {
        $cover = UPLOAD_PATH . 'uploads' . DS . date('Ymd') . DS . time() . rand(1000, 9999) . '.mp4';
        $data = explode(',', $data);
        $str = base64_decode($data[1]);
        if (!$str)
            responseJson([], 996);
        // 获取表单上传文件;
        $tmp = file_exists(UPLOAD_PATH . 'uploads');
        //判断uploads文件夹是否存在
        if (!$tmp)
            mkdir(UPLOAD_PATH . 'uploads');
        //判断文件夹是否存在
        if (!file_exists(UPLOAD_PATH . 'uploads' . DS . date('Ymd')))
            mkdir(UPLOAD_PATH . 'uploads' . DS . date('Ymd'));
        //文件写入
        $tmp = file_put_contents($cover, $str);
        //判断是否上传成功
        if (!$tmp)
            responseJson([], 6011);
        $images = str_replace(dirname(ROOT_PATH), '', $cover);
        return $images;
    } elseif (strpos($data, 'android')) {
        $cover = UPLOAD_PATH . 'uploads' . DS . 'apk' . DS . time() . rand(1000, 9999) . '.apk';
        $data = explode(',', $data);
        $base = $data[1];
        $str = base64_decode($base);
        if (!$str)
            responseJson([], 996);
        // 获取表单上传文件;
        $tmp = file_exists(UPLOAD_PATH . 'uploads');
        //判断uploads文件夹是否存在
        if (!$tmp)
            mkdir(UPLOAD_PATH . 'uploads');
        //判断文件夹是否存在
        if (!file_exists(UPLOAD_PATH . 'uploads' . DS . 'apk'))
            mkdir(UPLOAD_PATH . 'uploads' . DS . 'apk');
        //文件写入
        $tmp = file_put_contents($cover, $str);
        //判断是否上传成功
        if (!$tmp)
            responseJson([], 6011);
        $images = str_replace(dirname(ROOT_PATH), '', $cover);
        return $images;
    } else {
        $cover = UPLOAD_PATH . 'uploads' . DS . date('Ymd') . DS . time();
        $data = explode(',', $data);
        foreach ($data as $key => $val) {
            if (strlen($val) > 25) {
                $image[] = $val;
            }
        }

        if (empty($image)) {
            responseJson([], 1001);
        }
        foreach ($image as $value) {
            $str = base64_decode($value);


            if (!$str)
                responseJson([], 996);
            // 获取表单上传文件;
            $tmp = file_exists(UPLOAD_PATH . 'uploads');
            //判断uploads文件夹是否存在
            if (!$tmp)
                mkdir(UPLOAD_PATH . 'uploads');
            //判断文件夹是否存在
            if (!file_exists(UPLOAD_PATH . 'uploads' . DS . date('Ymd')))
                mkdir(UPLOAD_PATH . 'uploads' . DS . date('Ymd'));
            //文件写入
            $num = rand(1000, 9999);
            $tmp = file_put_contents($cover . $num . '.png', $str);
            //判断是否上传成功
            if (!$tmp)
                responseJson([], 6011);
            $images[] = str_replace(dirname(ROOT_PATH), '', $cover . $num . '.png');

        }
        return $images;
    }
}

/**
 * 生成作品版号字符串
 * @param  array $version_arr 摄影师编号
 * @param string $goods_num 作品数量
 * @param integer $goods_issue 作品最大版数
 * @return string $version_no 作品版号字符串
 */
function version_no($version_arr,$goods_num,$goods_issue = 900){
    if (empty($version_arr)){
        responseJson([],1009);
    }
//    print_r($version_arr);exit();
    if (empty($goods_num)){
        responseJson([],3093);
    }
    if (empty($goods_issue)){   //作品总版数不能为空
        responseJson([],3094);
    }
    $version_no = '';
    $y = ($goods_issue == 900) ? 201 : 1;
    for ($x = $y; $x <= $goods_issue; $x++){
        if (!in_array($x,$version_arr)){
            $goods_num = $goods_num - 1;
            if ($goods_num == 0){
                $version_no .= $x;
                break;
            }else {
                $version_no .= $x . ',';
            }
        }
    }
    $arr = explode(',',$version_no);
    $num = count($arr);
    if ($num < $goods_num){
        responseJson([],3092);
    }
    return $version_no;
}

/**
 * 生成作品版号字符串(平台赠送)
 * @param  array $version_arr 摄影师编号
 * @param string $goods_num 作品数量
 * @param integer $goods_issue 作品最大版数
 * @param integer $type 类型：1平台、2用户
 * @return string $version_no 作品版号字符串
 */
function versions($version_arr,$type,$goods_num = 1,$goods_issue = 200){
    if (empty($version_arr)){
        responseJson([],1009);
    }
    if (empty($goods_num)){
        responseJson([],3093);
    }
    if (empty($goods_issue)){   //作品总版数不能为空
        responseJson([],3094);
    }
    if (empty($type)){   //作品总版数不能为空
        responseJson([],1009);
    }
    $version_no = '';
    $y = ($type == 1) ? 2 : 1;
    for ($x = $y; $x <= $goods_issue; $x+=2){
        if (!in_array($x,$version_arr)){
            $goods_num = $goods_num - 1;
            if ($goods_num == 0){
                $version_no .= $x;
                break;
            }else {
                $version_no .= $x . ',';
            }
        }
    }
    $arr = explode(',',$version_no);
    $num = count($arr);
    if ($num < $goods_num){
        responseJson([],3092);
    }
    return $version_no;
}

/**
 * 生成作品版号字符串(购买时201-900号用完后)
 * @param  array $version_arr 摄影师编号
 * @param string $goods_num 作品数量
 * @param integer $goods_issue 作品最大版数
 * @param integer $type 类型：1平台、2用户
 * @return string $version_no 作品版号字符串
 */
function versions_no($version_arr,$goods_num = 1,$goods_issue = 200){
    if (empty($version_arr)){
        responseJson([],1009);
    }
    if (empty($goods_num)){
        responseJson([],3093);
    }
    if (empty($goods_issue)){   //作品总版数不能为空
        responseJson([],3094);
    }
    $version_no = '';
    for ($x = 1; $x <= $goods_issue; $x++){
        if (!in_array($x,$version_arr)){
            $goods_num = $goods_num - 1;
            if ($goods_num == 0){
                $version_no .= $x;
                break;
            }else {
                $version_no .= $x . ',';
            }
        }
    }
    return $version_no;
}

//PHP stdClass Object转array
function object_array($array) {
    if(is_object($array)) {
        $array = (array)$array;
    } if(is_array($array)) {
        foreach($array as $key=>$value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

//筛选用户可见作品
function screen($goods,$member){
    if (empty($goods)){
        responseJson([],1009);
    }
    if (empty($member)){
        responseJson([],1009);
    }
    foreach ($goods as $k => $v){
        if ($v['visibility'] != 6) {
            $visibility = explode(',', $v['visibility']);
            if (in_array(1,$visibility)){
                if (empty($member['tel'])){
                    unset($goods[$k]);
                    continue;
                }
            }
            if (in_array(2,$visibility)){
                if ($member['is_author'] == 3){
                    unset($goods[$k]);
                    continue;
                }
            }
            if (in_array(3,$visibility)){
                $third = Db::name('goods_third')->where('goods_id',$v['id'])->find();
                if (empty($third)){
                    responseJson([],1004);
                }
                $author_num = Db::name('order_goods')->where('member_id',$member['id'])->group('author_id')->count();
                $price = Db::name('order_goods')->field('sum(current_price) as price')->group('member_id')->where('member_id',$member['id'])->find();
                if (($author_num < $third['author_num']) || ($price['price'] < $third['price'])){
                    unset($goods[$k]);
                    continue;
                }
            }
            if (in_array(4,$visibility)){
                $fourth = Db::name('goods_fourth')->where('goods_id',$v['id'])->find();
                if (empty($fourth)){
                    responseJson([],1004);
                }
                $author_num = Db::name('order_goods')->alias('o')->join('goods g','g.id = o.goods_id','LEFT')->where('o.member_id',$member['id'])->where('g.type',$v['type'])->group('o.author_id')->count();
                $price = Db::name('order_goods')->alias('o')->join('goods g','g.id = o.goods_id','LEFT')->where('o.member_id',$member['id'])->where('g.type',$v['type'])->group('o.author_id')->field('sum(current_price) as price')->select();
                if ($author_num >= $fourth['author_num']){
                    if (empty($price)){
                        $this->responseJson([],1004);
                    }else{
                        $tmp = [];
                        foreach ($price as $key => $val){
                            if ($val['price'] < $fourth['price']){
                                $tmp[] = $val['price'];
                            }
                        }
                        if (!empty($tmp)){
                            unset($goods[$k]);
                            continue;
                        }
                    }
                }else{
                    unset($goods[$k]);
                    continue;
                }
            }
            if (in_array(5,$visibility)){
                $member_id = $member['id'];
                $fifth = Db::name('goods_fifth')->where('goods_id',$v['id'])->where("find_in_set('$member_id',member_id)")->find();
                if (empty($fifth)) {
                    unset($goods[$k]);
                    continue;
                }
            }
        }
    }
    if (!empty($goods)){
        $goods = array_values($goods);
    }
    return $goods;
}

//获取毫秒级时间戳
function getMillisecond() {
    list($t1, $t2) = explode(' ', microtime());
    return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
}

//查找某个值是否存在于多维数组中
function deep_in_array($value,$array)
{

    if(in_array($value,$array))
    {
        return true;
    }
    foreach($array as $row)
    {
        if(in_array($value,$row))
        {
            return true;
        }
    }
    return false;
}

/**
 * 验证银行卡号码格式
 * @param string $id_card 银行卡号码
 * @return boolean
 */
function is_bank($bank) {
    $chars = "/^(\d{16}|\d{19}|\d{17})$/";
    if (preg_match($chars, $bank)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 根据照片编号生成商品版号
 * @param string $photo_no 照片编号
 * @param integer $goods_id 作品ID
 * @param integer $goods_version 作品版型：1收藏版、2精品版、3极品版、4博物馆版
 * @param integer $version_no 作品版号
 * @return string $photo_version 商品版号
 */
function version_photo($photo_no,$goods_id,$goods_version,$version_no){
    if (empty($photo_no)) {  //照片编号不能为空
        responseJson([], 3081);
    }
    //商品ID不能为空
    if (empty($goods_id)) {
        responseJson([], 3000);
    }
    if (empty($goods_version)) { //作品版型不能为空
        responseJson([], 3008);
    }
    if (empty($version_no)) {    //商品版号不能为空
        responseJson([], 3165);
    }
    if (strlen($version_no) == 1) {
        $version_no = '000' . $version_no;
    } elseif (strlen($version_no) == 2) {
        $version_no = '00' . $version_no;
    } elseif (strlen($version_no) == 3) {
        $version_no = '0' . $version_no;
    }
    $version_num = '';  //商品总版数
    $version = '';  //商品版号标志
    if ($goods_version == 1) {  //如果商品是收藏版
        $version = 'S';
        $version_num = 1000;    //收藏版总版数固定1000版
    } elseif ($goods_version == 2) {    //如果商品是精品版
        $version = 'J';
        $version_num = Db::name('goods')->where('id', $goods_id)->field('quality_issue')->find();    //查询此作品精品版的总版数
        if (empty($version_num['quality_issue'])) {
            responseJson([], 1004);
        }
        $version_num = $version_num['quality_issue'];
    } elseif ($goods_version == 3) {    //如果商品是极品版
        $version = 'J';
        $version_num = Db::name('goods')->where('id', $goods_id)->field('best_issue')->find();   //查询此作品极品版的总版数
        if (empty($version_num['best_issue'])) {
            responseJson([], 1004);
        }
        $version_num = $version_num['best_issue'];
    } elseif ($goods_version == 4) {    //如果商品是博物馆版
        $version = 'J';
        $version_num = Db::name('goods')->where('id', $goods_id)->field('museum_issue')->find(); //查询此作品博物馆版的总版数
        if (empty($version_num['museum_issue'])) {
            responseJson([], 1004);
        }
        $version_num = $version_num['museum_issue'];
    }
    if (strlen($version_num) == 1) { //将版号不足四位数的拼接成四位字符串
        $version_num = '000' . $version_num;
    } elseif (strlen($version_num) == 2) {
        $version_num = '00' . $version_num;
    } elseif (strlen($version_num) == 3) {
        $version_num = '0' . $version_num;
    }
    $photo_version = 'Z' . $photo_no . $version . $version_no . '/' . $version_num;
    return $photo_version;
}